import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 25000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(997, error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (response.request.responseType === 'arraybuffer') {
      return response
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code && res.code !== 200) {
      // 50008: Illegal token; 50012: Other clients logged in; 401: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 401) {
        // to re-login
        MessageBox.confirm('您已退出登录，留在此页面还是重新登录？', '确认退出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        Message({
          message: res.error || res.message || '未知错误',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.error || res.message || '未知错误'))
    } else {
      return res
    }
  },
  error => {
    console.log(996, error) // for debug
    const res = error.response.data
    Message({
      message: res.error || res.messsage || error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

export async function download(response, filename) {
  // 读取response.header里的文件名
  let tempName = filename
  if (response.headers['content-disposition']) {
    tempName = response.headers['content-disposition'].split(';')[1].split('filename=')[1]
  }
  // 如果不是中文需要解码,URI编码需要decodeURI解码,GBK编码用iconv-lite插件解码
  tempName = decodeURI(tempName)

  // 获取数据流数据
  const blob = new Blob([response.data], { type: response.headers['content-type'] })

  var downloadElement = document.createElement('a')

  var href = window.URL.createObjectURL(blob) // 创建下载的链接

  downloadElement.href = href

  downloadElement.download = tempName // 下载后文件名

  document.body.appendChild(downloadElement)

  downloadElement.click() // 点击下载

  document.body.removeChild(downloadElement) // 下载完成移除元素

  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

/**
 *
 * @returns 接口根路径
 */
export function baseUrl() {
  return service.baseURL
}
